<template>
  <div>
    <!-- 城市列表 -->
    <div>
      <van-nav-bar
        title="城市列表"
        left-arrow
        fixed
        @click-left="$router.back()"
      />
      <div class="bottom">
        <van-index-bar :index-list="indexList">
          <div v-for="(item, key) in allObj" :key="key">
            <van-index-anchor :index="key">
              <span v-if="key === '#'" style="color: #a4a4a4">当前城市</span>
              <span v-else-if="key === '$'" style="color: #a4a4a4"
                >热门城市</span
              >
              <span v-else style="color: #a4a4a4">{{ key }}</span>
            </van-index-anchor>
            <van-cell
              @click="onclick(item1)"
              :title="item1.label"
              v-for="(item1, index) in item"
              :key="index"
            />
          </div>
        </van-index-bar>
      </div>
    </div>
  </div>
</template>

<script>
import { getCityList, getHotList } from '@/api/city'
export default {
  name: 'city-title',
  data() {
    return {
      indexList: [],
      allObj: {}
    }
  },
  async created() {
    const res1 = await getCityList({ level: 1 })
    console.log(res1)
    const res2 = await getHotList()
    const allObj = {
      '#': [],
      热: res2.body,
      A: [],
      B: [],
      C: [],
      D: [],
      E: [],
      F: [],
      G: [],
      H: [],
      I: [],
      J: [],
      K: [],
      L: [],
      M: [],
      N: [],
      O: [],
      P: [],
      Q: [],
      R: [],
      S: [],
      T: [],
      U: [],
      V: [],
      W: [],
      X: [],
      Y: [],
      Z: []
    }
    res1.body.forEach((item) => {
      // 找到short第一个字母toUpperCase()转为大写
      const key = item.short[0].toUpperCase()
      // 在重新放回allObj数组里
      allObj[key].push(item)
    })
    // 遍历对象for in
    for (const key in allObj) {
      // 判断
      if (allObj[key].length === 0) {
        // delete删除这一项
        delete allObj[key]
      }
    }
    console.log(allObj)
    this.indexList = Object.keys(allObj)
    this.allObj = allObj
  },
  methods: {
    onclick(city) {
      window.localStorage.setItem('city', JSON.stringify(city))
      this.$router.push('/article')
    }
  }
}
</script>

<style scoped lang="less">
.bottom {
  position: fixed;
  top: 45px;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: auto;
}
::v-deep .van-index-bar__index {
  margin: 6px 0;
}
::v-deep .van-index-anchor {
  font-size: 18px;
}
::v-deep .van-icon-arrow-left:before {
  color: #fff;
}
::v-deep .van-nav-bar {
  background-color: #21b97a;
}
::v-deep .van-nav-bar__title {
  color: #fff;
}
</style>
